<template>
    <div class="dir-share-page">
        <div class="dir-share-top" v-resize="SizeChange">
            <span class="dir-name" @click="backDirRoot"
                :class="{ 'dir-name-active': breadPath.length == 0 }">{{ docInfo.name }}</span>
            <div class="bread-box">
                <template v-for="(item, index) in breadPath" :key="index">
                    <div class="bread-item" @click="backItem(item, index)" v-if="index >= startRender"
                        :id="`bread-item-${index}`">
                        <svg class="next-icon">
                            <use xlink:href="#keowledge-a-zu4701"></use>
                        </svg>
                        <span class="knowledge-name hover-back"
                            :class="[index == (breadPath.length - 1) && 'knowledge-name-last']"
                            :title="item.name">{{ item.name }}</span>
                    </div>
                </template>
                <div class="bread-item" v-if="startRenderList.length > 0">
                    <svg class="next-icon">
                        <use xlink:href="#keowledge-a-zu4701"></use>
                    </svg>
                    <el-icon class="hover-back" ref="moreBread" @click="showMoreBread">
                        <MoreFilled />
                    </el-icon>
                </div>
            </div>
        </div>
        <div class="dir-share-body">
            <div class="dir-share-left" :style="{ width: `${treeWidth}px` }">
                <div class="knowledge-tree-search" v-resize="searchSizeChange">
                    <div class="search-box">
                        <el-input v-model="treeSearch" placeholder="搜索">
                            <template #prefix>
                                <svg class="search-icon">
                                    <use xlink:href="#keowledge-sousuo"></use>
                                </svg>
                            </template>
                        </el-input>
                    </div>
                </div>
                <div class="tree-box">
                    <el-scrollbar ref="elTreeScrollRef" @scroll="treeScroll">
                        <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" ref="treeRef"
                            :filter-node-method="filterNode" v-loading="treeLoading" node-key="id">
                            <template #default="{ node, data }">
                                <div class="custom-tree-node">
                                    <svg class="svg-icon" aria-hidden="true">
                                        <use v-bind:xlink:href="getIcon(data.type, data.nameSuffix)"></use>
                                    </svg>
                                    <div class="node-info">
                                        <div v-tooltip-auto-show>
                                            <el-tooltip :content="data.name" effect="light">
                                                <div class="name">{{ data.name }}</div>
                                            </el-tooltip>
                                        </div>
                                        <div class="time">{{ data.createTime }}</div>
                                    </div>
                                </div>
                            </template>
                        </el-tree>
                    </el-scrollbar>
                </div>
            </div>
            <div class="dir-share-right" :style="{ width: getCurrentWidth }"
                :class="[checkNode.type == 'document_upload' && checkNode.nameSuffix == 'txt' && 'txt-right-box']">
                <el-scrollbar ref="viewFileScroll" @scroll="bodyScroll"
                    :style="{ paddingRight: ['document_html', 'md'].includes(checkNode.type) ? '8px' : '0px' }">
                    <fileViewShow ref="fileViewShowRef"
                        v-if="checkNode.id && ['knowledge', 'directory'].indexOf(checkNode.type) == -1"
                        :docInfo="checkNode" v-loading="fileLoading" @renderFinish="renderFinish"
                        @refreshScrollState="refreshScrollState" @setMenuList="setMenuList" style="padding-right:8px;"
                        :isScreen="isScreen" :isDir="true"></fileViewShow>
                    <jvs-empty v-if="!checkNode.id" imgSrc="@/assets/images/common/noCheck.png"
                        text="在左侧目录选择文件进行预览"></jvs-empty>
                </el-scrollbar>
            </div>
            <div class="knowledge-other">
                <menuList v-show="!showMenuBut && menuList.length != 0"
                    v-if="['document_html', 'md'].includes(checkNode.type)" @close="changeMenuStatus"
                    :menuList="menuListArr" @clickScroll="scrollNode" :show="!showMenuBut" ref="menuListRef"></menuList>
            </div>
            <div class="menu-button-box" v-if="showMenuBut && ['document_html', 'md'].includes(checkNode.type)"
                @click="changeMenuStatus">
                <svg class="menu-icon">
                    <use xlink:href="#keowledge-a-zu7044"></use>
                </svg>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    unref,
    reactive,
    toRefs,
    watch,
    watchEffect,
    nextTick,
    onMounted,
    computed,
    getCurrentInstance,
    onUnmounted
} from 'vue'
import { getLibTree } from '@/api/knowledge'
import { useRoute } from "vue-router"
import { Tree } from 'element-plus/es/components/tree-v2/src/types';
import fileViewShow from '@/views/common/fileView.vue'
import menuList from '@/views/common/menuList.vue'
import { setSessionStore, getSessionStore, delSessionStore } from '@/utils/store'
interface Tree {
    label: string,
    children?: Tree[]
}
const route = useRoute();

const emit = defineEmits(["renderFinish"])
const props = defineProps({
    propData: {
        type: String,
        default: ''
    },
    docInfo: {
        type: Object,
        default() {
            return {}
        }
    }
})
const moreBreadPopover = ref(false)
const breadPath = ref<any[]>([])
const startRender = ref(0)
const startRenderList = ref([])
const treeData = ref([])
const treeLoading = ref(false)
const treeSearch = ref('')
const treeRef = ref()
const defaultProps = {
    children: 'children',
    label: 'name',
}
const checkNode = ref({})
const bodyScrollTop = ref(0)
const cliclMenuScroll = ref(false)
const showMenuBut = ref(false)
const menuListArr = ref([])
const viewFileScroll = ref()
const fileViewShowRef = ref()
const fileLoading = ref(false)
const treeWidth = ref(240)
const enterFolderId = ref()
const enterFolder = ref(false)
const folderObj = ref<any>({})
const originNodeList = ref({})
const menuListRef = ref()
const sessionKey = ref('')
onMounted(() => {
    sessionKey.value = route.params.shareKey as string
    enterFolderId.value = getSessionStore({ name: sessionKey.value })
    init()
})
onUnmounted(() => {
    delSessionStore({ name: sessionKey.value })
})
watch(() => enterFolderId.value, (newV) => {
    setSessionStore({ name: sessionKey.value, content: enterFolderId.value })
})
const getCurrentWidth = computed(() => {
    let str = `calc(100% - ${treeWidth.value}px)`
    if (!showMenuBut.value && checkNode.value.id && menuListArr.value.length != 0) {
        str = `calc(100% - ${treeWidth.value}px - 268px)`
    } else {
        str = `calc(100% - ${treeWidth.value}px)`
    }
    return str
})
function init() {
    treeLoading.value = true
    treeData.value = []
    const queryId = enterFolderId.value || props.docInfo.id
    getLibTree({
        id: queryId
    }).then(res => {
        if (res.data.code == 0) {
            if (res.data.data.dcLibrary.type == "directory") {
                folderObj.value = res.data.data.dcLibrary
            }
            breadPath.value = []
            let started = false
            res.data.data.directoryStructure.forEach((item: any) => {
                if (started) {
                    breadPath.value.push(item)
                }
                if (props.docInfo.id == item.id) {
                    started = true
                }
            })
            if (res.data.data.dcLibrary.type == "directory" && folderObj.value.id != props.docInfo.id) {
                breadPath.value.push({
                    id: folderObj.value.id,
                    name: folderObj.value.name,
                    type: folderObj.value.type,
                })
            }
            treeData.value = res.data.data.data
        }
        treeLoading.value = false
    }).catch(err => {
        treeLoading.value = false
    })
    emit('renderFinish')
}
function renderFinish() {
    viewFileScroll.value.setScrollTop(0)
    refreshScrollState()
    fileLoading.value = false
    emit('renderFinish')
}
watch(treeSearch, (val) => {
    treeRef.value!.filter(val)
})
watchEffect(() => {
    [breadPath.value]
    calcShowBreadNum()
})
function SizeChange() {
    calcShowBreadNum()
}
function calcShowBreadNum() {
    startRender.value = 0
    nextTick(() => {
        let renderNum = 0, renderList = [], renderWidth = 0
        const sumWidth = document.getElementById('bread-box')?.clientWidth - 122
        if (sumWidth > 0) {
            let i = breadPath.value?.length - 1
            for (; i >= 0; i--) {
                const domWidth = document.getElementById(`bread-item-${i}`)?.clientWidth
                renderWidth += domWidth
                if (renderWidth < sumWidth) {
                    renderNum += 1
                } else {
                    break
                }
            }
            if (renderWidth < sumWidth) {
                startRender.value = 0
                startRenderList.value = []
            } else {
                if (renderNum != 0) {
                    startRender.value = (breadPath.value?.length - renderNum) || 0
                } else {
                    startRender.value = breadPath.value?.length - 1
                }
                let arr = []
                breadPath.value?.forEach((item, index) => {
                    if (index < startRender.value) {
                        arr.push(item)
                    }
                })
                startRenderList.value = arr
            }
        }
    })
}
function showMoreBread() {
    moreBreadPopover.value = true
}
// 回到根路径下
function backDirRoot() {
    enterFolderId.value = ''
    enterFolder.value = false
    init()
}
function backItem(item, index) {
    moreBreadPopover.value = false
    if (item.pathId.length == 0) {
        enterFolderId.value = ''
        enterFolder.value = false
    } else {
        if (item.id == enterFolderId.value || item.id == folderObj.value.id) return
        enterFolderId.value = item.id
    }
    init()
}
function filterNode(value: string, data: Tree) {
    if (!value) return true
    return data.name.includes(value)
}
function handleNodeClick(data: Tree) {
    menuListArr.value = []
    showMenuBut.value = false
    bodyScrollTop.value = 0
    cliclMenuScroll.value = false
    if (['knowledge', 'directory'].indexOf(data?.type) != -1) {
        enterFolderId.value = data.id
        init()
    } else {
        fileLoading.value = true
        if (checkNode.value.id == data.id) {
            fileViewShowRef.value?.refreshFile()
        } else[
            checkNode.value = data
        ]
        nextTick(() => {
            refreshScrollState()
        })
    }
}
function refreshScrollState() {
    setTimeout(() => {
        viewFileScroll.value.update()
    }, 100)
}
function setMenuList(val, nodeList) {
    showMenuBut.value = false
    if (val.length != 0 && JSON.stringify(val) != '{}') {
        menuListArr.value = val
    } else {
        menuListArr.value = []
    }
    originNodeList.value = nodeList || []
    setTimeout(() => {
        viewFileScroll.value.update()
    }, 200)
}
function changeMenuStatus() {
    if (showMenuBut.value) {
        showMenuBut.value = false
    } else {
        showMenuBut.value = true
    }
}
function bodyScroll({ scrollTop, scrollLeft }) {
    bodyScrollTop.value = scrollTop
    if (cliclMenuScroll.value) return
    if (checkNode.value.type == 'document_html') {
        let lastId = ''
        originNodeList.value.forEach((item, index) => {
            if (item.innerHTML != '<br>') {
                if (['H1', 'H2'].indexOf(item.nodeName) > -1 && item.offsetTop - bodyScrollTop.value <= 14) {
                    lastId = item.id
                }
            }

        })
        if (lastId) {
            unref(menuListRef)?.setCurrentKey(lastId)
        }
    } else if (checkNode.value.type == 'md') {
        let lastId = ''
        originNodeList.value.forEach((item, index) => {
            if (document.getElementById(`h${item.level}-${item.id}`) && document.getElementById(`h${item.level}-${item.id}`).offsetTop - bodyScrollTop.value <= 14) {
                lastId = item.id
            }

        })
        if (lastId) {
            unref(menuListRef)?.setCurrentKey(lastId)
        }
    }
}
function scrollNode(node) {
    cliclMenuScroll.value = true
    // 编辑页布局更改后不需要减掉页面顶部偏移量
    // viewFileScroll.value.setScrollTop(node.offsetTop - 118)
    if (checkNode.value.type == 'document_html') {
        viewFileScroll.value.setScrollTop(document.getElementById(node.id).offsetTop)
    } else if (checkNode.value.type == 'md') {
        viewFileScroll.value.setScrollTop(document.getElementById(node.nodeName + '-' + node.id).offsetTop)
    }
    setTimeout(() => {
        cliclMenuScroll.value = false
    }, 100)
}
</script>
<style lang="scss" scoped>
.dir-share-page {
    position: relative;
    height: 100%;
    width: 100%;

    ::v-deep(.empty-box) {
        min-height: auto !important;
    }

    .dir-share-top {
        height: 30px;
        padding-left: 24px;
        line-height: 30px;
        margin-bottom: 4px;
        display: flex;
        align-items: center;
        overflow: hidden;

        .dir-name {
            cursor: pointer;
            font-size: 14px;
            color: #363b4c;
            cursor: pointer;
            word-break: keep-all;
            max-width: 260px;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .dir-name-active {
            @include SourceHanSansCN-Bold;
        }

        .bread-box {
            display: flex;
            align-items: center;
            overflow: hidden;

            .bread-item {
                display: flex;
                align-items: center;

                .el-icon {
                    cursor: pointer;
                }

                .next-icon {
                    width: 16px;
                    min-width: 16px;
                    height: 16px;
                }

                .knowledge-name {
                    font-size: 14px;
                    color: #363b4c;
                    cursor: pointer;
                    word-break: keep-all;
                    max-width: 260px;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }

                .knowledge-name-last {
                    @include SourceHanSansCN-Bold;
                }
            }
        }
    }

    .dir-share-body {
        display: flex;
        height: calc(100% - 34px);
        position: relative;

        .dir-share-left {
            .knowledge-tree-search {
                margin-right: 16px;
                margin-bottom: 8px;
                margin-left: 24px;

                .search-box {
                    display: flex;
                    align-items: center;

                    .search-icon {
                        width: 14px;
                        height: 14px;
                    }

                    ::v-deep(.el-input) {
                        .el-input__wrapper {
                            box-shadow: none !important;
                            background-color: #F5F6F7 !important;
                        }
                    }
                }
            }

            .tree-box {
                height: calc(100% - 38px);
                padding-left: 8px;

                ::v-deep(.el-scrollbar>.el-scrollbar__wrap>.el-scrollbar__view) {
                    height: 100%;
                }

                .el-tree {
                    height: 100%;
                    padding-right: 8px;

                    ::v-deep(.el-tree-node__expand-icon) {
                        // display: none !important;
                        width: 1px !important;
                        height: 52px !important;
                        margin: 0px !important;
                        padding: 0px !important;
                    }

                    ::v-deep(.el-tree-node__content) {
                        height: 52px;
                        border-radius: 4px;

                        &:hover {
                            background: #DDEAFF !important;
                        }
                    }

                    ::v-deep(.is-current>.el-tree-node__content) {
                        background: #DDEAFF !important;
                    }

                    ::v-deep(.el-tree-node__content:has(.custom-active)) {
                        background: #DDEAFF !important;
                    }

                    ::v-deep(.custom-active) {
                        .action-box {
                            .share {
                                visibility: hidden !important;
                            }

                            .more {
                                visibility: visible !important;
                                z-index: 2;
                                color: #1E6FFF;
                                background: #EDF4FF;
                                border-radius: 4px 4px 4px 4px;
                            }
                        }
                    }

                    ::v-deep(.custom-tree-node) {
                        display: flex;
                        align-items: center;
                        padding-left: 16px;
                        width: 100%;

                        .node-info {
                            margin-left: 12px;
                            width: calc(214px - 44px);
                            overflow: hidden;

                            .name {
                                font-size: 14px;
                                color: #363B4C;
                                width: calc(100% - 0px);
                                text-overflow: ellipsis;
                                overflow: hidden;
                                white-space: nowrap;
                            }

                            .time {
                                width: calc(100% - 0px);
                                font-size: 12px;
                                color: #6F7588;
                                text-overflow: ellipsis;
                                overflow: hidden;
                                white-space: nowrap;
                            }
                        }

                        &:hover {
                            .action-box {
                                .share {
                                    visibility: hidden;
                                }

                                .more {
                                    visibility: visible;
                                    z-index: 2;
                                }
                            }

                            .no-auth-aciton-box {
                                .share {
                                    visibility: visible;
                                }

                                .more {
                                    visibility: hidden;
                                    z-index: 2;
                                }
                            }
                        }

                        .action-box {
                            width: 20px;
                            height: 20px;
                            cursor: pointer;
                            border: none;
                            position: relative;

                            .action-icon {
                                width: 20px;
                                height: 20px;
                                outline: none !important;
                            }

                            .share {
                                visibility: visible;
                            }

                            .more {
                                font-size: 20px;
                                position: absolute;
                                left: 0px;
                                visibility: hidden;

                                &:hover {
                                    background: #EDF4FF;
                                    border-radius: 4px 4px 4px 4px;
                                    color: #1E6FFF;
                                }
                            }
                        }

                        .svg-icon {
                            width: 20px;
                            height: 20px;
                        }
                    }
                }
            }
        }

        .dir-share-right {
            border-left: 1px solid #f5f6f7;
            height: calc(100vh - 98px);

            ::v-deep(.el-scrollbar>.el-scrollbar__wrap>.el-scrollbar__view) {
                height: 100%;
            }

            .file-view-box {
                min-height: calc(100vh - 104px);

                ::v-deep(.view-file-office) {
                    height: calc(100vh - 104px) !important;
                }

                ::v-deep(.iframe-class) {
                    height: calc(100vh - 104px) !important;
                }

                ::v-deep(.mind-map-read) {
                    height: calc(100vh - 104px) !important;
                }

                ::v-deep(.view-file-mindElixir) {
                    height: calc(100vh - 104px) !important;
                }

                ::v-deep(.meta2d-body) {
                    height: calc(100vh - 104px) !important;
                }

                ::v-deep(#mainIframe) {
                    height: calc(100vh - 104px) !important;
                }
            }
        }

        .txt-right-box {
            ::v-deep(.el-scrollbar>.el-scrollbar__wrap>.el-scrollbar__view) {
                height: auto;
            }
        }

        .knowledge-other {
            position: fixed;
            right: 0px;
            height: calc(100vh - 112px);
            max-width: 268px;
            z-index: 6;
        }

        .menu-box {
            height: auto;
        }

        .menu-button-box {
            position: fixed;
            width: 36px;
            height: 36px;
            background: #F5F6F7;
            border-radius: 6px 0px 0px 6px;
            right: 0px;
            top: 150px;
            z-index: 199;
            cursor: pointer;

            .menu-icon {
                width: 36px;
                height: 36px;
                cursor: pointer;
            }
        }
    }
}
</style>